package com.opensns.test;

import org.json.JSONArray;
import org.json.JSONObject;

import com.opensns.android.OauthAccessToken;
import com.opensns.android.Parameters;
import com.opensns.renren.Renren;

public class RenrenActivity extends TestActivty {
	
	@Override
	protected void onInit() {
		super.onInit();
		
		Renren.APP_KEY = "19b5fef0cc334d59a3d7112a8c60e29c";
		Renren.APP_SECRET = "f1bbaa2f6758408284ee831078e2e6c0";
		Renren.SCOPES = new String[]{ "status_update" };
		mRenren = Renren.getInstance();
		
		mToken = Renren.restoreAccessToken(this);
		if (OauthAccessToken.isTokenValid(mToken)) {
			mRenren.setAccessToken(mToken);
			updateTokenInfo(mToken);
		}
	}

	@Override
	protected void callAuthorize() {
		if (mToken == null) {
			mRenren.authorize(getActivityContext(), mAuthCallback);
		}	
	}

	@Override
	protected void onAuthorizeSuccess() {
		mToken = mRenren.getAccessToken();
		Renren.storeAccessToken(getActivityContext(), mToken);
		updateTokenInfo(mToken);
	}

	@Override
	protected void sendGetUserNameRequest() {
		if (mToken != null) {
			Parameters params = new Parameters();
			params.add("method", "users.getInfo");
			params.add("v", "1.0");
			params.add("access_token", mToken.accessToken);
			params.add("format", "JSON");
			params.add("fields", "name");
			mRenren.requestAsync(this, params, mGetNameCallback);
		}
	}

	@Override
	protected String getUserNameFromResponse(String response) {		
		try {
			JSONArray json = new JSONArray(response);
			JSONObject first = json.getJSONObject(0);
			return first.optString("name", "");
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return null;
	}

	@Override
	protected void publishContent(String text) {
		if (mToken != null) {
			Parameters params = new Parameters();
			params.add("method", "status.set");
			params.add("v", "1.0");
			params.add("access_token", mToken.accessToken);
			params.add("format", "JSON");
			params.add("status", text);
			mRenren.requestAsync(getActivityContext(), params, mPublishCallback);
		}
	}

	Renren mRenren;
	OauthAccessToken mToken;
}
